<?php

namespace app\shop\model;

class Order extends \ShopModel
{
    protected $table = 'sh_order';

    protected $pk = 'order_id';

    protected $autoWriteTimestamp = true;
    protected $updateTime = false;
    protected $createTime = 'create_at';

    protected $insert = ['order_sn'];


    public function orderGoods()
    {
        return $this->hasMany('OrderGoods', 'order_id', 'order_id');
    }


    protected function setOrderSnAttr()
    {
        return $this->generateOrderSn();
    }

    public function generateOrderSn()
    {
        $dateString = sprintf('%09d', time() - 1544745600);

        mt_srand((double) microtime() * 10000);
        $randString = sprintf('%05d', mt_rand(1, 99999));

        $orderNoTmp = substr($dateString, 4, 3)
            . substr($randString, 0, 2)
            . substr($dateString, 0, 2)
            . substr($dateString, 7)
            . substr($dateString, 2, 2)
            . substr($randString, 2);

        $count = $this->where([
            'order_sn' => $orderNoTmp,
        ])->count('order_sn');
        if ($count) return $this->generateOrderSn();

        return $orderNoTmp;
    }
}
